<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("modules.report.service_report") }}
    </PageTitle>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('modules.report.normal_sheet')" name="first" />
      <el-tab-pane :label="$t('modules.report.invalid_sheet')" name="second" />
      <el-tab-pane :label="$t('modules.report.log_sheet')" name="three"
        ><failLog
      /></el-tab-pane>
    </el-tabs>
    <el-card
      v-if="activeName !== 'three'"
      shadow="never"
      :body-style="{ padding: '0px' }"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="totalCount"
      @current-change="handleCurrentChange"
    >
      <el-form class="p-4" inline :model="dataForm">
        <el-form-item>
          <el-input
            ref="name"
            v-model="userName"
            clearable
            :placeholder="$t('common.customer_name')"
            @clear="clearSearchName"
            @focus="openCustomerList"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="selectTime"
            type="monthrange"
            unlink-panels
            format="YYYY-MM"
            value-format="yyyyMM"
            range-separator="-"
            :start-placeholder="$t('common.start_time')"
            :end-placeholder="$t('common.end_time')"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="customerType"
            clearable
            :placeholder="$t('customer.customer_type')"
          >
            <el-option :label="$t('customer.demo_customer')" :value="'DEMO'" />
            <el-option :label="$t('customer.normal_customer')" :value="'NORMAL'" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="activeName === 'first'">
          <el-select v-model="status" clearable :placeholder="$t('common.status')">
            <el-option
              v-for="item in reportStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-permission="{ permission: ['10401004.MANAGE', '10401004.QUERY'] }"
            type="primary"
            class="w-8"
            @click="getReportList"
          >
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('modules.report.generate_report')"
            placement="top"
          >
            <el-button
              v-permission="{ permission: '10401004.MANAGE' }"
              type="primary"
              class="w-8"
              @click="openGenerateReport"
            >
              <svg-icon icon-class="Files" />
            </el-button>
            <!-- <el-button type="primary" size="small" icon="el-icon-files"   @click="generateReport"></el-button> -->
          </el-tooltip>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="reportList" stripe>
        <el-table-column prop="month" :label="$t('common.month')" />
        <el-table-column :label="$t('common.customer_name')" prop="userName">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("common.customer_type") }}:
                      {{ scope.row.characterCode }} (ID: {{ scope.row.keyId }})</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.userName }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="confirmState" :label="$t('common.status')">
          <template v-slot="scope">
            <el-tag
              size="small"
              :type="
                scope.row.confirmState == '0'
                  ? 'warning'
                  : scope.row.confirmState == '1'
                  ? 'success'
                  : scope.row.confirmState == '2'
                  ? ''
                  : scope.row.confirmState == '3'
                  ? 'danger'
                  : 'info'
              "
              disable-transitions
            >
              {{
                scope.row.confirmState == "0"
                  ? $t("modules.report.report_status_list.unconfirmed")
                  : scope.row.confirmState == "1"
                  ? $t("modules.report.report_status_list.confirmed")
                  : scope.row.confirmState == "2"
                  ? $t("modules.report.report_status_list.overtime_confirmed")
                  : scope.row.confirmState == "3"
                  ? $t("modules.report.report_status_list.rejected")
                  : $t("modules.report.report_status_list.invalid")
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.creation_time')" prop="creDate">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span>{{ scope.row.creTime }}</span
                    ><br /></div
                ></template>
                <div>
                  {{ scope.row.creDate }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-dropdown class="align-middle" trigger="click">
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-permission="{
                      permission: ['10401004.MANAGE', '10401004.QUERY'],
                    }"
                    @click="
                      getDetail(scope.row.reportId, scope.row.userName, scope.row.month)
                    "
                  >
                    <svg-icon icon-class="View" />
                    {{ $t("modules.report.report_detail") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="
                      scope.row.confirmState === 3 &&
                      scope.row.canBeChangedToUnconfirmed == true
                    "
                    v-permission="{ permission: '10401004.MANAGE' }"
                    @click="editReportState(scope.row)"
                  >
                    <svg-icon icon-class="View" />
                    {{ $t("modules.report.edit_report") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.confirmState === 4"
                    v-permission="{ permission: '10401004.MANAGE' }"
                    @click="regenerateReport(scope.row)"
                  >
                    <svg-icon icon-class="Refresh" />
                    {{ $t("modules.report.generate_report") }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.confirmState === 0 || scope.row.confirmState === 3"
                    v-permission="{ permission: '10401004.MANAGE' }"
                    @click="invalidReport(scope.row)"
                  >
                    <svg-icon icon-class="CircleClose" />
                    {{ $t("modules.report.invalid_report") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>

        <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="$t('modules.report.report_detail')"
              placement="top"
            >
              <el-button
                v-permission="{
                  permission: ['10401004.MANAGE', '10401004.QUERY'],
                }"
                style="color: #8c939d; font-size: 18px; margin-right: 5px"
                type="text"
                size="small"
                icon="el-icon-info"
                @click.native="
                  () =>
                    $router.push({
                      path: '/service-management/customer-report/detail',
                      query: {
                        reportId: scope.row.reportId,
                        name: scope.row.userName,
                        month: scope.row.month,
                      },
                    })
                "
              />
            </el-tooltip> -->
        <!-- <el-tooltip
              class="item"
              effect="dark"
              :content="$t('modules.report.edit_report')"
              placement="top"
            >
              <el-button
                v-if="
                  scope.row.confirmState === 3 &&
                  scope.row.canBeChangedToUnconfirmed == true
                "
                v-permission="{ permission: '10401004.MANAGE' }"
                style="color: #8c939d; font-size: 18px; margin-right: 5px"
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="editReportState(scope.row)"
              />
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('modules.report.generate_report')"
              placement="top"
            >
              <el-button
                v-if="scope.row.confirmState === 4"
                v-permission="{ permission: '10401004.MANAGE' }"
                style="color: #8c939d; font-size: 18px; margin-right: 5px"
                type="text"
                size="small"
                icon="el-icon-refresh"
                @click="regenerateReport(scope.row)"
              />
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('modules.report.invalid_report')"
              placement="top"
            >
              <el-button
                v-if="scope.row.confirmState === 0 || scope.row.confirmState === 3"
                v-permission="{ permission: '10401004.MANAGE' }"
                style="color: #8c939d; font-size: 18px; margin-right: 5px"
                type="text"
                size="small"
                icon="el-icon-s-release"
                @click="invalidReport(scope.row)"
              />
            </el-tooltip> -->
      </el-table>
    </el-card>
    <!-- 修改report状态 -->
    <el-dialog
      :title="$t('modules.report.edit_report')"
      v-model="editReportVisible"
      width="40%"
    >
      <el-form ref="reportForm" :model="reportForm" label-position="top">
        <el-form-item :label="$t('modules.report.report_status') + ':'">
          <template>
            <el-radio v-model="reportStatus" label="UnConfirmed">{{
              $t("modules.report.report_status_list.unconfirmed")
            }}</el-radio>
            <!-- <el-radio v-model="reportStatus" label="confirmed">Confirmed</el-radio> -->
            <el-radio v-model="reportStatus" label="Rejected">{{
              $t("modules.report.report_status_list.rejected")
            }}</el-radio>
          </template>
        </el-form-item> </el-form
      ><template #footer>
        <span class="dialog-footer">
          <el-button text @click="editReportVisible = false">{{
            $t("common.cancel")
          }}</el-button>
          <el-button
            v-permission="{ permission: '10401004.MANAGE' }"
            type="primary"
            @click="editReportInfo"
            >{{ $t("common.confirm") }}</el-button
          >
        </span></template
      >
    </el-dialog>
    <!-- 获取手动生成report的对话框 -->
    <generate-report
      ref="generateReport"
      v-model="generateReportVisible"
      @refresh="getReportList"
    />
    <customer-list
      ref="customerList"
      v-model="getUserNameVisible"
      @confirmSelect="confirmUserName"
    />
  </div>
</template>

<script>
import {
  getReport,
  editReportState,
  regenerateReport,
  getInvalidReport,
} from "@/api/report";
import { toTime, toTenYMD } from "@/utils/index";
import failLog from "./components/fail-log";
import CustomerList from "@/views/service-management/components/customer-list";
import GenerateReport from "@/views/service-management/customer-report/components/generate-report";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  name: "ServiceManagementCustomerReport",
  components: {
    failLog,
    CustomerList,
    GenerateReport,
    PageTitle,
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      confirmRegenerateLoading: false,
      activeName: "first",
      loading: false,
      getReportVisible: false,
      getUserNameVisible: false,
      editReportVisible: false,
      generateReportVisible: false,
      totalCount: undefined,
      pageNo: 1,
      pageSize: 10,
      userName: "",
      userData: {
        characterCode: "",
        keyId: "",
      },
      reportForm: {
        month: "",
        userName: "",
        characterCode: "",
        keyId: "",
        reportId: "",
        confirmState: "",
      },
      customerType: "",
      status: "",
      reportList: [],
      reportStatus: "",
      selectTime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t("common.last_month"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              end.setMonth(end.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t("common.half_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t("common.one_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    reportStatusList() {
      return [
        { value: 0, label: this.$t("modules.report.report_status_list.unconfirmed") },
        { value: 1, label: this.$t("modules.report.report_status_list.confirmed") },
        {
          value: 2,
          label: this.$t("modules.report.report_status_list.overtime_confirmed"),
        },
        { value: 3, label: this.$t("modules.report.report_status_list.rejected") },
      ];
    },
    settingList() {
      return {
        columns: [
          {
            title: this.$t("common.short_name"),
            code: "SHORT_NAME",
          },
          {
            title: this.$t("common.address"),
            code: "ADDRESS",
          },
          {
            title: this.$t("common.link_man"),
            code: "LINKMAN",
          },
          {
            title: this.$t("common.mobile"),
            code: "MOBILE",
          },
          {
            title: this.$t("common.email"),
            code: "EMAIL",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [],
      };
    },
  },
  mounted() {
    this.$store.commit("app/ADD_KEEP_ALIVE_LIST", "ServiceManagementCustomerReport");
    this.getReportList();
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "detailReport") {
      this.$store.commit("app/REMOVE_KEEP_ALIVE_LIST", "ServiceManagementCustomerReport");
    }
    next();
  },
  activated() {
    this.getReportList();
  },
  methods: {
    showHeader(label) {
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    openGenerateReport() {
      this.generateReportVisible = true;
      this.$nextTick(() => {
        this.$refs.generateReport.init();
      });
    },
    // 切换sheet页
    handleClick(tab, event) {
      if (this.activeName !== "three") {
        this.getReportList();
      } else {
        // 进入generate failed logs接口
      }
    },
    // 获取report列表
    getReportList() {
      this.loading = true;
      let start, end;
      if (this.selectTime === null) {
        start = end = "";
      } else if (this.selectTime.length === 0) {
        start = end = "";
      } else {
        start = this.selectTime[0].toString();
        end = this.selectTime[1].toString();
      }
      const params_valid = {
        characterCode: this.userData.characterCode,
        keyId: this.userData.keyId,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        confirmState: this.status,
        startMonth: start,
        endMonth: end,
        customerType: this.customerType,
      };
      const params_invalid = {
        characterCode: this.userData.characterCode,
        keyId: this.userData.keyId,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        startMonth: start,
        endMonth: end,
        customerType: this.customerType,
      };
      if (this.activeName === "first") {
        getReport(params_valid)
          .then((res) => {
            this.totalCount = res.total;
            this.reportList = res.list;
            for (let i = 0; i < this.reportList.length; i++) {
              this.reportList[i].creDate = toTenYMD(this.reportList[i].creTime);
              this.reportList[i].creTime = toTime(this.reportList[i].creTime);
            }
            this.loading = false;
          })
          .catch((err) => {
            this.$message.error(err.message);
            this.loading = false;
          });
      } else {
        getInvalidReport(params_invalid)
          .then((res) => {
            this.totalCount = res.total;
            this.reportList = res.list;
            for (let i = 0; i < this.reportList.length; i++) {
              this.reportList[i].creDate = toTenYMD(this.reportList[i].creTime);
              this.reportList[i].creTime = toTime(this.reportList[i].creTime);
            }
            this.loading = false;
          })
          .catch((err) => {
            this.$message.error(err.message);
            this.loading = false;
          });
      }
    },
    // 处理分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getReportList();
    },
    // 修改report状态
    editReportState(detail) {
      this.editReportVisible = true;
      this.reportForm.reportId = detail.reportId;
      this.confirmState = detail.confirmState;
      if (detail.confirmState === 0) {
        this.reportStatus = "Uncomfirmed";
      } else {
        this.reportStatus = "Rejected";
      }
    },
    // 确认修改report状态
    editReportInfo() {
      if (this.reportStatus === "UnConfirmed") {
        this.reportForm.confirmState = 0;
      } else {
        this.reportForm.confirmState = 3;
      }
      editReportState(this.reportForm.reportId, this.reportForm.confirmState)
        .then((res) => {
          this.editReportVisible = false;
          this.getReportList();
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    // 关闭Customer Name的对话框
    customerNameClose() {
      this.getUserNameVisible = false;
    },
    // 清空Customer Name搜索框内容
    clearSearchName() {
      this.userData.characterCode = "";
      this.userData.keyId = "";
      this.userName = "";
      this.getReportList();
    },
    // 确定获取的UserName
    confirmUserName(detail) {
      // 手动生成report的customer name
      this.userData.characterCode = "OPERATOR";
      this.userData.keyId = detail.keyId;
      this.userName = detail.name;
      this.getUserNameVisible = false;
    },
    // 清空report里的Customer Name
    clearReportName() {
      this.reportForm.characterCode = "";
      this.reportForm.keyId = "";
      this.reportForm.userName = "";
      this.$forceUpdate();
    },
    openCustomerList() {
      this.customerListVisible = true;
      this.$nextTick(() => {
        this.$refs.customerList.openDialog();
      });
    },
    // 重新生成report
    regenerateReport(detail) {
      // 加个确认
      this.$confirm(this.$t("tip_content.regenerate_report"), {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      }).then(() => {
        const data = {
          characterCode: detail.characterCode,
          keyId: detail.keyId,
          month: detail.month,
        };
        regenerateReport(data)
          .then((res) => {
            this.$message.success(this.$t("common.success"));
            this.getReportList();
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      });
    },
    // 作废report
    invalidReport(detail) {
      // 加个确认
      this.$confirm(this.$t("tip_content.invalid_report"), {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          editReportState(detail.reportId, 4)
            .then((res) => {
              this.getReportList();
              this.$message.success(this.$t("common.success"));
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    //前往详情界面
    getDetail(reportId, userName, month) {
      this.$router.push({
        path: "/service-management/customer-report/detail",
        query: {
          reportId: reportId,
          name: userName,
          month: month,
        },
      });
    },
  },
};
</script>

<style scoped>
/* .box {
      margin: 0.2em 0.5em;
      } */
.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}
.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}
.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.operateIcon {
  display: inline-block;
  width: 40px;
  color: #2c7be5;
}
.operateIcon :hover {
  color: #484ff3;
  cursor: pointer;
}
</style>
